# -*- coding:utf-8 -*
from django.shortcuts import render
from django.utils.http import urlquote, urlencode
from django.db import transaction
from django.conf import settings
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status as status_code
from rest_framework import authentication
from tb_forms.functions.receiver import is_valid
from tb_forms.functions.analyze import ParserXLS, ParserXLSX
from django.db.models import Q
from tb_forms.models import *
import json
import os
import base64
import time, datetime
import requests
from method.method import case, WorkflowError, work_build

from django.views.decorators.csrf import csrf_exempt
from tb_forms.functions.forms_num import get_num, get_pdf, post_msn
from tb_forms.functions.db import geshihua
from wfs.function.produce_pdf import delete_pdf, born_pdf
import threading
import uuid
from PIL import Image
import logging
from tb_forms.functions.log import log
import re
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


# Create your views here.
# from tb_forms.views import *
#
# logger = logging.getLogger(__name__)
# logger.info('username')

def response_origin(data, status):
    response = Response(data, status)
    response['Access-Control-Allow-Origin'] = '*'
    return response


@api_view(http_method_names=['POST'])
@csrf_exempt
@log(__name__)
def analyze(request):
    # print(request.method)
    if request.method == 'GET':
        raise TypeError
    elif request.method == "POST":
        excel = request.FILES.get("filename")
        # print(type(excel),str(excel))
        file_type = str(excel).split('.')
        # print(file_type[-1])
        # path = os.path.join("mysite", "st", "download", datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")+'.'+file_type[-1])
        path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_EXCEL,
                            datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + '.' + file_type[-1])
        # path = settings.MEDIA_ROOT+settings.FORMS_EXCEL+datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") + '.' + file_type[-1]
        # path  = os.path.join(os.path.dirname(__file__), datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")+'.'+file_type[-1])
        # print(path)
        context = {}
        try:
            statu1 = status_code.HTTP_202_ACCEPTED
            with open(path, 'wb') as flhd:
                flhd.write(excel.read())
            if file_type[-1] == 'xlsx':

                files = ParserXLSX(path)
            elif file_type[-1] == 'xls':
                # try:
                #     files = ParserXLS(path)
                # except:
                files = ParserXLS(path)
            context["data"] = files.parser()
            # print(context["data"])
            context["status"] = status_code.HTTP_202_ACCEPTED

        except Exception as e:
            # print(e)
            context["status"] = status_code.HTTP_406_NOT_ACCEPTABLE
            context["error"] = str(e)
            statu1 = status_code.HTTP_406_NOT_ACCEPTABLE
        finally:
            if os.path.exists(path):
                os.remove(path)
        return response_origin(context, status=statu1)


@api_view(http_method_names=['GET', 'POST'])
@csrf_exempt
@log(__name__)
def color(request):
    # print(request.method)
    if request.method == 'POST':
        try:

            data = request.data
            s = TbColor()
            s.color = data['color']
            s.desc = data['desc']
            s.save()
            return response_origin({'statue': status_code.HTTP_201_CREATED, 'data': 'Success'},
                                   status=status_code.HTTP_201_CREATED)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": "value null"},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'GET':
        results = TbColor.objects.all()
        list1 = []

        for j in results:
            dicts = {'id': j.id, 'color': j.color, 'desc': j.desc}
            list1.append(dicts)
        return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)


@api_view(http_method_names=['GET'])
@csrf_exempt
@log(__name__)
def colors(request, pk):
    if request.method == 'GET':
        list1 = []
        try:
            results = TbColor.objects.filter(id=pk)
            # print(results)
            if results:
                for j in results:
                    dicts = {'id': j.id, 'color': j.color, 'desc': j.desc}
                    list1.append(dicts)
                return response_origin({"status": "True", "data": list1}, status=status_code.HTTP_200_OK)
            else:
                return response_origin({"status": "False", "message": "value null"},
                                       status=status_code.HTTP_204_NO_CONTENT)
        except Exception as e:
            # print(e)
            return response_origin({"status": "False", "message": "value null"},
                                   status=status_code.HTTP_400_BAD_REQUEST)


@api_view(http_method_names=['GET', 'POST'])
@csrf_exempt
@log(__name__)
def logo(request):
    if request.method == 'GET':
        result = TbFormheader.objects.all()
        list1 = []

        for i in result:
            dicts = {"id": i.id, "img_name": i.header_img, "img_url": i.header_url}
            list1.append(dicts)
        return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status_code.HTTP_200_OK)

    if request.method == 'POST':
        img_name = request.FILES.get('filename')
        image = str(img_name).split('.')
        # print(img_name)
        uid = str(uuid.uuid1())
        name = uid + '.' + image[-1]
        path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, name)
        try:
            with open(path, 'wb') as flhd:
                flhd.write(img_name.read())
                flhd.close()

            img_url = settings.FORMS_URL.split('/', 1)[-1] + name
            s = TbFormheader()
            s.header_img = img_name
            s.header_url = img_url
            s.save()

            return response_origin({"status": status_code.HTTP_200_OK, "message": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            message = str(e)
            return response_origin({"status": status_code.HTTP_202_ACCEPTED, "message": message},
                                   status=status_code.HTTP_202_ACCEPTED)
            # else:
            #     return response_origin({"status":"False","message":"wrong commit way"})


@api_view(http_method_names=['GET', 'DELETE'])
@csrf_exempt
@log(__name__)
def logos(request, pk):
    if request.method == 'GET':
        result = TbFormheader.objects.filter(id=pk)
        list1 = []
        if result:
            for i in result:
                dicts = {"id": i.id, "img_name": i.header_img, "img_url": i.header_url}
                list1.append(dicts)
            return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)
        else:
            return response_origin({"status": status_code.HTTP_202_ACCEPTED, "message": "value null"},
                                   status=status_code.HTTP_202_ACCEPTED)
    if request.method == 'DELETE':
        try:
            TbFormheader.objects.filter(id=pk).delete()
            # name =TbFormheader.objects.filter(id =pk).values('header_url')[0]['header_url'].split['/'][-1]
            # path = os.path.join(settings.MEDIA_ROOT,settings.FORMS_FILE,name)
            #
            # os.remove(path)
            return response_origin({"status": status_code.HTTP_200_OK, "data": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            str(e)
            return response_origin({"status": status_code.HTTP_202_ACCEPTED, "data": str(e)},
                                   status=status_code.HTTP_202_ACCEPTED)


@api_view(http_method_names=['GET', 'DELETE', 'PUT'])
@csrf_exempt
@log(__name__)
def tmplcategory(request, pk):
    if request.method == 'GET':
        list1 = []
        try:
            results = TbFormtype.objects.filter(statue=1).filter(id=pk)
            # print(results)
            if results:
                for j in results:
                    dicts = {'id': j.id, 'type': j.forms_type, 'type_english': j.type_english, 'type_code': j.type_code}
                    list1.append(dicts)
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_200_OK)
            else:
                return response_origin({"status": status_code.HTTP_204_NO_CONTENT, "message": "value null"},
                                       status=status_code.HTTP_204_NO_CONTENT)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": str(e)},
                                   status=status_code.HTTP_400_BAD_REQUEST)

    elif request.method == 'DELETE':
        try:
            TbFormtype.objects.filter(id=pk).update(statue=0)
            return response_origin({"status": status_code.HTTP_200_OK, "message": " null"},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'PUT':
        try:
            data = request.data
            type = data['type'] if 'type' in data.keys() else TbFormtype.objects.filter(id=pk).values('forms_type')[0]
            english = data['type_english'] if 'type_english' in data.keys() else \
                TbFormtype.objects.filter(id=pk).values('type_english')[0]
            code = data['type_code'] if 'type_code' in data.keys() else \
                TbFormtype.objects.filter(id=pk).values('type_code')[0]
            TbFormtype.objects.filter(id=pk).update(forms_type=type, type_english=english, type_code=code)
            return response_origin({"status": status_code.HTTP_200_OK, "message": " null"},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)


@api_view(http_method_names=['POST', 'GET'])
@csrf_exempt
@log(__name__)
def tmplcategorys(request):
    # print(request.method)
    if request.method == 'GET':
        list1 = []
        results = TbFormtype.objects.filter(statue=1)

        for i in results:
            dicts = {'id': i.id, 'type': i.forms_type, 'type_english': i.type_english, 'type_code': i.type_code}
            list1.append(dicts)
        return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)
    elif request.method == 'POST':
        try:
            data = request.data
            type = data['type']
            english = data['type_english']
            code = data['type_code']
            s = TbFormtype()
            type_id = int(len(TbFormtype.objects.all())) + 1
            if type != None:
                s.forms_type = type
                s.type_english = english
                s.type_code = code
                s.statue = 1
                s.type_id = type_id
                s.save()
                return response_origin({'statue': status_code.HTTP_201_CREATED, 'data': 'Success'},
                                       status=status_code.HTTP_201_CREATED)
            else:
                return response_origin({'status': status_code.HTTP_406_NOT_ACCEPTABLE, 'data': 'not null'},
                                       status=status_code.HTTP_406_NOT_ACCEPTABLE)
        except Exception as e:
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": str(e)},
                                   status=status_code.HTTP_400_BAD_REQUEST)


from wfs.models import Workflownode


@api_view(http_method_names=['GET', 'PUT', 'POST', 'DELETE'])
@csrf_exempt
@log(__name__)
def tmpl(request, pk):
    if request.method == 'GET':
        try:
            results = TbForms.objects.filter(id=pk).values('table_name', 'table_type__forms_type',
                                                           'table_type', 'layout',
                                                           'table_content', 'version', 'status',
                                                           'desc', 'id', 'workflow_id', 'workflow__workflow_type',
                                                           'workflow__name', 'create_time', 'modify_time')
            data = ''

            # if Workflow.objects.filter(id=results[0]['workflow_id'],workflow_type='self'):
            #       data = Workflownode.objects.filter(workflow_id=results[0]['workflow_id']).values()

            # print(data)
            list1 = []
            if results:
                for i in results:
                    if i['status'] == 1:
                        i['status_name'] = '生效'
                    elif i['status'] == 2:
                        i['status_name'] = '草稿'
                    elif i['status'] == 0:
                        i['status_name'] = '禁用'
                    i['workflow_type'] = i['workflow__workflow_type']
                    i['type'] = {'type_name': i['table_type__forms_type'], 'type_id': i['table_type']}
                    i['workflow'] = {'workflow_id': i['workflow_id'], 'workflow_name': i['workflow__name']}
                    i['create_time'] = i['create_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"])
                    i['modify_time'] = i['modify_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"])
                    del i['workflow__name'], i['table_type__forms_type'], i['table_type'], i['workflow_id'], i[
                        'workflow__workflow_type']
                    # i['workflow_content']=data
                    list1.append(i)

                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_200_OK)
            else:
                return response_origin({"status": status_code.HTTP_204_NO_CONTENT, "message": "value null"},
                                       status=status_code.HTTP_204_NO_CONTENT)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": str(e)},
                                   status=status_code.HTTP_400_BAD_REQUEST)
    elif request.method == 'POST':
        try:
            form_model = \
                TbForms.objects.filter(id=pk).values('table_name', 'workflow_id', 'table_type_id', 'table_content',
                                                     'version', 'desc', 'sign_type')[0]
            data = request.data
            tbn = data['name'] if 'name' in data.keys() else form_model['table_name']
            tbc = data['content'] if 'content' in data.keys() else form_model['table_content']
            tbt = data['type'] if 'type' in data.keys() else form_model['table_type_id']
            twid = data['workflow_id'] if 'workflow_id' in data.keys() else form_model['workflow_id']
            desc = data['desc'] if 'desc' in data.keys() else form_model['desc']
            sign_type = data['sign_type'] if 'sign_type' in data.keys() else form_model['sign_type']
            layout = data['layout'] if 'layout' in data.keys() else form_model['layout']
            # layout = data['layout'] if 'layout' in data.keys() else ""
            # workflow_type = data['workflow_type'] if 'workflow_type' in data.keys() else ''
            # workflow_content =data['workflow_content'] if 'workflow_content'  in data.keys() else ''

            # old_version = form_model['version']
            # a = old_version[1:]
            # b = float(a) + 1
            # version = old_version.replace(a, str(b))
            TbForms.objects.filter(id=pk).update(table_name=tbn, table_content=tbc, desc=desc,
                                                 table_type_id=tbt, workflow_id=twid, sign_type=sign_type
                                                 , layout=layout)
            return response_origin({"status": status_code.HTTP_202_ACCEPTED}, status=status_code.HTTP_202_ACCEPTED)
        except Exception as e:
            mes = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": mes},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'PUT':
        try:
            data = request.data
            status = int(data['status'])
            name = TbForms.objects.filter(id=pk).values('table_name')[0]['table_name']
            name_len = TbForms.objects.filter(table_name=name).all().count()
            status_len = TbForms.objects.filter(table_name=name, status=1).all().count()
            if status == 1:
                if status_len != 0:
                    if name_len > 1:
                        raise WorkflowError("模板重名，请先禁止其中一个模板")
                else:
                    if not TbForms.objects.filter(id=pk).values('workflow_id')[0]['workflow_id']:
                        raise WorkflowError("請將設置模板路由設置完整后再啟用!")
                    TbForms.objects.filter(id=pk).update(status=1)
            elif status == 0:
                TbForms.objects.filter(id=pk).update(status=0)
            elif status == 2:
                TbForms.objects.filter(id=pk).update(status=2)

            return response_origin({"status": status_code.HTTP_202_ACCEPTED}, status=status_code.HTTP_202_ACCEPTED)
        except Exception as e:
            mes = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": mes},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'DELETE':
        try:
            TbForms.objects.filter(id=pk).update(status=3)

            return response_origin({"status": status_code.HTTP_202_ACCEPTED}, status=status_code.HTTP_202_ACCEPTED)
        except Exception as e:
            mes = str(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": mes},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)


@api_view(http_method_names=['POST', 'GET'])
@csrf_exempt
@log(__name__)
def tmpls(request):
    # print(request.method)
    if request.method == 'POST':
        try:
            data = request.data
            sign_type = data['client'] if 'client' in data.keys() else 'false'
            layout = data['layout'] if 'layout' in data.keys() else ""
            now = datetime.datetime.now()
            s = TbForms()
            s.table_name = data['name']
            s.table_content = data['content']
            s.creater = request.user
            s.status = 2
            s.desc = data['desc']
            s.workflow_id = data['workflow_id']
            s.create_time = now
            s.table_type_id = data['type']
            s.modify_time = now
            s.sign_type = sign_type
            s.layout = layout
            if TbForms.objects.filter(table_name=data['name']).exclude(status=3).all().count() != 0:
                old_version = TbForms.objects.filter(table_name=data['name']).order_by('-id').values('version')[0][
                    'version']
                # print(old_version)
                a = old_version[1:]
                b = float(a) + 1
                s.version = old_version.replace(a, str(b))
            else:
                s.version = 'V1.0'

            s.save()
            return response_origin({'statue': status_code.HTTP_201_CREATED, 'data': 'Success'},
                                   status=status_code.HTTP_201_CREATED)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'GET':
        try:
            status = int(request.GET.get('type', None))
            # print(status)
            if status == 0:
                results = TbForms.objects.filter(status=1).values('table_name', 'table_type__forms_type', 'table_type',
                                                                  'version', 'status', 'desc', 'id', 'workflow_id',
                                                                  'creater', 'create_time', 'modify_time', 'sign_type')
                # print(results)
            elif status == 1:
                results = TbForms.objects.exclude(status=3).values('table_name', 'table_type__forms_type', 'table_type',
                                                                   'version', 'status', 'desc', 'id', 'workflow_id',
                                                                   'creater',
                                                                   'create_time', 'modify_time', 'sign_type')

            list1 = []
            if results:
                for i in results:
                    try:
                        username = TbUser.objects.filter(username=i['creater']).values('last_name')[0]['last_name']
                    except:
                        username = None
                    i['creater_name'] = username
                    i['create_time'] = i['create_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"]) if i[
                        'create_time'] else ''
                    i['modify_time'] = i['modify_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"]) if i[
                        'modify_time'] else ''
                    if i['status'] == 1:
                        i['status_name'] = '生效'
                    elif i['status'] == 2:
                        i['status_name'] = '草稿中'
                    elif i['status'] == 0:
                        i['status_name'] = '失效'
                    list1.append(i)
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_200_OK)
            else:
                # print(111)
                return response_origin({"status": status_code.HTTP_204_NO_CONTENT, "message": "value null"},
                                       status=status_code.HTTP_200_OK)
        except Exception as e:
            # print(e)
            return response_origin({"status": status_code.HTTP_400_BAD_REQUEST, "message": str(e)},
                                   status=status_code.HTTP_400_BAD_REQUEST)


@api_view(http_method_names=['GET', 'POST'])
@csrf_exempt
@log(__name__)
def forms(request):
    if request.method == 'GET':

        # client = request.META['HTTP_USER_AGENT']
        # print(client)
        get_type = (request.GET.get('type', None))
        page = int(request.GET.get('page', 1))  # 页数默认为首页
        per_num = int(request.GET.get('per_num', 20))  # 每页的个数默认20个
        type = get_type
        select = request.GET.get('select', None)
        if type == '0':
            if select:
                select = '%' + select + '%'
                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,b.status,\
                  c.status,c.action FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                  where  a.wrecord_id = b.id and b.id = c.workflow_record_id  and c.approver = '{0}' and c.`status`=0 OR (a.card_id LIKE '{1}' OR a.name LIKE '{1}' OR a.applicant LIKE                    '{1}') AND a.customer_id is NULL AND a.project_id is NULL  order by c.start_time DESC ".format(
                    request.user, select)
            else:
                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,b.status,\
                                  c.status,c.action FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                                  where   a.wrecord_id = b.id and b.id = c.workflow_record_id  and c.approver = '{0}' and c.`status`=0  AND a.customer_id is NULL AND a.project_id is NULL  order by c.start_time DESC ".format(
                    request.user)

        elif type == '1':
            if select:
                select = '%' + select + '%'

                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,\
                    b.status,c.status,c.action\
                    FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                    where a.customer_id is NULL AND a.project_id is NULL  AND a.wrecord_id = b.id and b.id = c.workflow_record_id  and a.applicant = '{0}' AND  (a.card_id LIKE '{1}' OR a.name LIKE '{1}' OR a.applicant LIKE '{1}') ORDER BY c.start_time DESC".format(
                    request.user, select)
            else:
                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,\
                                    b.status,c.status,c.action\
                                    FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                                    where a.customer_id is NULL AND a.project_id is NULL  AND a.wrecord_id = b.id and b.id = c.workflow_record_id  and a.applicant = '{0}'ORDER BY c.start_time DESC".format(
                    request.user)

        elif type == '2':
            # born_pdf('D:/浏览器下载/images.jpg','D:/浏览器下载/output2.pdf')
            if select:
                select = '%' + select + '%'
                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,b.status,\
                              c.status,c.action FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                              where a.customer_id is NULL AND a.project_id is NULL  AND a.wrecord_id = b.id and b.id = c.workflow_record_id  and c.approver = '{0}' and c.`status`=1 AND  (a.card_id LIKE '{1}' OR a.name LIKE '{1}' OR a.applicant LIKE '{1}') ORDER BY c.start_time DESC".format(
                    request.user, select)
            else:
                sql = "SELECT a.card_id,a.id,a.`name`,a.applicant,a.wrecord_id,b.create_time,a.degree,c.username as approve,c.approver,c.end_time,b.username,b.status,\
                              c.status,c.action FROM tb_applyform as a,tb_workflowrecord as b,tb_workflow_approval_record as c \
                              where a.customer_id is NULL AND a.project_id is NULL  AND a.wrecord_id = b.id and b.id = c.workflow_record_id  and c.approver = '{0}' and c.`status`=1 ORDER BY c.start_time DESC".format(
                    request.user)
        return response_origin({"status": status_code.HTTP_200_OK, "data": geshihua(sql, type, page, per_num)[0],
                                'page_count': geshihua(sql, type, page, per_num)[1],
                                "count": geshihua(sql, type, page, per_num)[3],
                                'page': geshihua(sql, type, page, per_num)[2]}, status=status_code.HTTP_200_OK)

    elif request.method == 'POST':
        # try:
        site = request.user.site
        # print(time.ctime())

        host_ip = request.META['HTTP_HOST']

        data = request.data

        id = data['tmpl_id']

        url = data['url'] if 'url' in data.keys() else ""
        userList = data['userList'] if 'userList' in data.keys() else ""

        mode = data['mode'] if 'mode' in data.keys() else ""  # 模板还是草稿模式
        draft_id = data['draft_id'] if 'draft_id' in data.keys() else ""  # 草稿id

        if userList == 'undefined':
            userList = None

        form_model = \
            TbForms.objects.filter(id=id).values('table_name', 'workflow_id', \
                                                 'table_type_id', 'table_content', 'desc', 'sign_type', 'layout')[0]

        workflowid = form_model['workflow_id'] if not userList else ""
        name = form_model['table_name']
        layout = form_model['layout']

        sign_type = form_model['sign_type']
        if sign_type != 'true':
            sign_type = 'false'

        content = data['content']
        type_id = form_model['table_type_id']
        desc = data['desc'] if 'desc' in data.keys() else ""
        org = data['org'] if 'org' in data.keys() else ""

        html = data['html'] if 'html' in data.keys() else ""

        # print("BEFORE: %s" % html)
        # html = html.\
        #     replace("\r", "\r\n").\
        #     replace("<br>", "\r\n").\
        #     replace("&nbsp;", " ").\
        #     replace("&lt", "<").replace("&gt", ">")
        # html = """<html><head><meta charset="utf8"></head><body>%s</body></html>""" % html

        # print("AFTER: %s" % html)
        creator = request.user
        degree = form_model['desc']
        try:
            image_statu = data['sign_image']
        except:
            image_statu = 'Y'
        filelist, up_file = [], []

        # print(time.ctime())

        card_id = get_num(site, type_id, id)  # 表单编号

        for i in range(1, 7):
            filename = request.FILES.get('filename' + str(i), None)

            if filename == None:
                fileurl = None
                url_name = None
            else:

                file = str(filename).split('.')
                url_name = file[0] + '(' + card_id + str(i) + ')' + '.' + file[-1]
                path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, url_name)  # 文件名:转码+表单编号

                with open(path, 'wb') as flhd:
                    flhd.write(filename.read())
                    flhd.close()

                fileurl = {'href': 'http://' + host_ip + settings.FORMS_URL + url_name, 'name': str(filename)}
            filelist.append(fileurl)
            up_file.append(url_name)
        null, false, true = '', '', ''
        print(111)
        wflrecondid, message = work_build(eval(request.POST.get('data', '[]')), '', 'sssss', card_id, request.user,
                                          id)  # case(creator, desc, org, workflowid, userList,id,card_id)
        print(222)
        url = url + str(wflrecondid)
        if degree == 'general':
            html_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '.html')
            pdf_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '1.pdf')
            get_pdf(html_path, pdf_path, html, layout, url)
            os.remove(html_path)
        else:
            if mode == 'draft':
                draft_model = TbFormdraft.objects.filter(id=int(draft_id)).values('file1')[0]
                if draft_model['file1'] == None or draft_model['file1'] == '':
                    file_pdf = filelist[0]
                else:
                    file_pdf = eval(draft_model['file1'])
                if file_pdf['href'].split('.')[-1] != 'pdf':
                    html_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '.html')
                    # img_file = re.sub(r"\w+.\/\/\d+.\d+.\d+.\d+.\d+\/[a-zA-Z]{0,5}", settings.MEDIA_ROOT,
                    #                   file_pdf['href'])
                    # signer = Image.open(img_file)
                    # w, h = signer.size
                    # signer.close()
                    html = """<img src="%s" >""" % (file_pdf['href'])
                    pdf_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '1.pdf')
                    get_pdf(html_path, pdf_path, html, layout, url)
                    os.remove(html_path)
                else:
                    pdf_path = settings.MEDIA_ROOT + file_pdf['href'].split('files')[1]
            else:
                if filelist[0]['href'].split('.')[-1] != 'pdf':
                    html_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '.html')
                    # img_file = re.sub(r"\w+.\/\/\d+.\d+.\d+.\d+.\d+\/[a-zA-Z]{0,5}" ,settings.MEDIA_ROOT, filelist[0]['href'])
                    # print(img_file)
                    # signer = Image.open(img_file)
                    # w, h = signer.size
                    # signer.close()
                    html = """<img src="%s" >""" % (filelist[0]['href'])
                    pdf_path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, card_id + '1.pdf')
                    get_pdf(html_path, pdf_path, html, layout, url)
                    os.remove(html_path)
                else:
                    pdf_path = settings.MEDIA_ROOT + filelist[0]['href'].split('files')[1]

        if message == '202':
            return response_origin({"status": status_code.HTTP_202_ACCEPTED, 'data': wflrecondid},
                                   status=status_code.HTTP_201_CREATED)

        s = TbApplyform()
        s.card_id = card_id
        s.layout = layout
        s.name = name
        s.form_content = content

        s.degree = degree
        s.apply_type = sign_type
        s.wrecord_id = wflrecondid
        s.sign_image = image_statu
        s.applicant = creator
        s.form_id = id
        s.apply_time = datetime.datetime.now()
        s.is_form = 1
        s.pdf = [{'name': '', 'href': pdf_path}]
        if mode == "draft":
            draft_model = TbFormdraft.objects.filter(id=int(draft_id)).values('file1', 'file2', \
                                                                              'file3', 'file4', \
                                                                              'file5', 'file6')[0]
            s.file1 = draft_model['file1'] if degree != 'general'  else {
                'href': 'http://' + host_ip + settings.FORMS_URL + card_id + '1.pdf', 'name': ''}
            s.file2 = draft_model['file2'] if draft_model['file2'] != None else filelist[1]
            s.file3 = draft_model['file3'] if draft_model['file3'] != None else filelist[2]
            s.file4 = draft_model['file4'] if draft_model['file4'] != None else filelist[3]
            s.file5 = draft_model['file5'] if draft_model['file5'] != None else filelist[4]
            s.file6 = draft_model['file6'] if draft_model['file6'] != None else filelist[5]
        else:
            s.file1 = filelist[0] if filelist[0] != None else {
                'href': 'http://' + host_ip + settings.FORMS_URL + card_id + '1.pdf', 'name': ''}
            s.file2 = filelist[1]
            s.file3 = filelist[2]
            s.file4 = filelist[3]
            s.file5 = filelist[4]
            s.file6 = filelist[5]
        s.save()

        from wfs.models import ReminderLog
        message['message']['url'] = "../templates/module1/index.html#/form:" + str(s.id)
        message['content'][0]['from_id'] = s.id
        message['content'][0]['from_mo'] = s.card_id
        message['content'][0]['from_name'] = s.name

        log = ReminderLog.objects.create(no=card_id, rectime=datetime.datetime.now(), applicant=request.user.username,
                                         user=message['to'], name=request.user.last_name,
                                         title=message['message']['title'],
                                         type=message['message']['type'], url=message['message']['url'], status=0,
                                         num=1)
        message['message']['id'] = log.id
        # requests.get('http://' + settings.MQTT + '/?topic=st/message&qos=2&message=' + str(message))
        # message1 = threading.Thread(
        #     target=post_msn, args=(str(message)))
        # message1.setDaemon(True)
        # message1.start()



        from wfs.function import produce_pdf
        # if filelist[0] == None:
        #     pdf_file= pdf_path
        #     # pdf_file = ''
        # else:
        #     pdf_file = settings.MEDIA_ROOT + settings.FORMS_FILE + up_file[0]

        # pdf_file = 'C:/Users/Alan/Desktop/333.pdf'
        try:
            pdf_file = settings.MEDIA_ROOT + settings.FORMS_FILE + pdf_path.split('/')[-1]
            pdf_list = [pdf_file]
            produce_pdf.form_pdf(wflrecondid, pdf_list)
        except:
            return response_origin({"status": status_code.HTTP_202_ACCEPTED, "message": '此PDF无法操作，请重新换个PDF文件'},
                                   status=status_code.HTTP_202_ACCEPTED)

        # pdf = threading.Thread(target=produce_pdf.form_pdf, args=(wflrecondid, pdf_file))
        # pdf.setDaemon(True)
        # pdf.start()

        return response_origin({"status": status_code.HTTP_201_CREATED}, status=status_code.HTTP_201_CREATED)
        # except Exception as e:
        #     return response_origin({"status": status_code.HTTP_202_ACCEPTED, "message": str(e)},
        #                            status=status_code.HTTP_202_ACCEPTED)


@api_view(http_method_names=['GET', 'PUT'])
@log(__name__)
def form(request, pk):
    if request.method == 'GET':
        list1 = []
        try:
            results = TbApplyform.objects.filter(id=pk).values('id', 'form_content', 'card_id', 'file1', 'file2',
                                                               'wrecord_id', 'name',
                                                               'file3', 'file4', 'file5', 'file6', 'form__desc',
                                                               'applicant',
                                                               'apply_time', 'degree', 'sign_image')

            if results:
                for i in results:
                    i['file1'] = None if i['degree'] == 'general' else eval(str(i['file1']))
                    i['file2'] = eval(str(i['file2']))
                    i['file3'] = eval(str(i['file3']))
                    i['file4'] = eval(str(i['file4']))
                    i['file5'] = eval(str(i['file5']))
                    i['file6'] = eval(str(i['file6']))
                    i['post_type'] = i['form__desc']
                    i['apply_time'] = i['apply_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"])
                    i['applicant_name'] = TbUser.objects.filter(username=i['applicant']).all()[0].last_name
                    del i['form__desc'], i['degree']
                    list1.append(i)
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_200_OK)
            else:
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_204_NO_CONTENT)
        except Exception as e:
            return response_origin({"status": status_code.HTTP_404_NOT_FOUND, "data": str(e)},
                                   status=status_code.HTTP_404_NOT_FOUND)


    elif request.method == 'PUT':
        pass


@api_view(http_method_names=['GET', 'POST'])
@csrf_exempt
@log(__name__)
def file_upload(request):
    try:
        if request.method == "POST":
            filename = request.FILES.getlist('filename')
            app_id = request.data['id']
            username = request.data['username']
            path = settings.PATH
            formfile = TbApplyform.objects.filter(id=app_id)
            filearray = formfile[0].file6
            if filearray:
                filearray = eval(filearray)
            else:
                filearray = {}
            filearray[username] = []
            if filename == None:
                fileurl = None
            else:
                for row in filename:
                    with open(path + row.name, 'wb') as flhd:
                        flhd.write(row.read())
                        flhd.close()

            formfile.update(file6=filearray)
            return response_origin({"status": status_code.HTTP_200_OK, "data": 111}, status=status_code.HTTP_200_OK)
    except Exception as e:
        return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "data": str(e)},
                               status=status_code.HTTP_406_NOT_ACCEPTABLE)


@api_view(http_method_names=['GET'])
@csrf_exempt
@log(__name__)
def datasource(request):
    results = TbDatasource.objects.all()

    list1 = []
    for i in results:
        dicts = {'Sourceid': i.id, 'api': i.api, 'apiName': i.apiname}
        list1.append(dicts)
        return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)


@api_view(http_method_names=['GET'])
@csrf_exempt
@log(__name__)
def item(request):
    try:
        pk = request.GET['Source']
        results = TbSourcelist.objects.filter(source=pk).all()
        list1 = []
        if results:
            for i in results:
                dicts = {'apiparamname': i.apiparamname, 'apiparamdescription': i.apiparamdescription}
                list1.append(dicts)
            return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)
    except Exception as e:
        return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                               status=status_code.HTTP_406_NOT_ACCEPTABLE)


@api_view(http_method_names=['POST', 'GET'])
@csrf_exempt
@log(__name__)
def parser(request):
    if request.method == 'POST':
        list1 = []
        data = request.data
        try:
            if data['Action'] == 'Or':
                results = TbUser.objects.filter(
                    Q(username__icontains=data['UserID']) | Q(last_name__contains=data['UserName'])).filter(
                    status_id=100).values('username', 'ext', 'tbuserorg__org__org_code',
                                          'tbuserorg__org__org_name', 'last_name')
                for i in results:
                    i['UserID'] = i['username']
                    i['UserName'] = i['last_name']
                    i['UserExt'] = i['ext']
                    i['OrgName'] = i['tbuserorg__org__org_name']
                    i['OrgCode'] = i['tbuserorg__org__org_code']
                    del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                        'tbuserorg__org__org_code']
                    list1.append(i)
            if data['Action'] == 'And':
                results = TbUser.objects.filter(
                    Q(username__icontains=data['UserID']) | Q(last_name__contains=data['UserName'])).filter(
                    status_id=100).values('username',
                                          'ext',
                                          'tbuserorg__org__org_code',
                                          'tbuserorg__org__org_name',
                                          'last_name')
                for i in results:
                    i['UserID'] = i['username']
                    i['UserName'] = i['last_name']
                    i['UserExt'] = i['ext']
                    i['OrgName'] = i['tbuserorg__org__org_name']
                    i['OrgCode'] = i['tbuserorg__org__org_code']
                    del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                        'tbuserorg__org__org_code']
                    list1.append(i)
            return response_origin({"status": status_code.HTTP_200_OK, "data": list1}, status=status_code.HTTP_200_OK)

        except Exception as e:
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)

    if request.method == 'GET':

        Userid = request.GET.get('UserID', '')
        try:
            list1 = []
            if Userid == '1':
                page = request.GET.get('page', '')
                results = TbUser.objects.filter(status_id=100).values('id', 'username', 'ext',
                                                                      'tbuserorg__org__org_code',
                                                                      'tbuserorg__org__org_name',
                                                                      'last_name')
                if page:
                    paginator = Paginator(results, 15)
                else:
                    paginator = Paginator(results, len(results))
                    page = 1
                for i in paginator.page(page):
                    i['id'] = i['id']
                    i['UserID'] = i['username']
                    i['UserName'] = i['last_name']
                    i['UserExt'] = i['ext']
                    i['OrgName'] = i['tbuserorg__org__org_name']
                    i['OrgCode'] = i['tbuserorg__org__org_code']
                    i['Date'] = datetime.datetime.now().strftime('%Y-%m-%d')
                    i['Datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                        'tbuserorg__org__org_code']
                    list1.append(i)
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1, 'page':
                    {'count': paginator.count, 'page': int(page), 'page_number': paginator.page_range[-1]}},
                                       status=status_code.HTTP_200_OK)
            elif Userid == '':
                results = TbUser.objects.filter(username=request.user).filter(status_id=100).values('username',
                                                                                                    'ext',
                                                                                                    'tbuserorg__org__org_code',
                                                                                                    'tbuserorg__org__org_name',
                                                                                                    'last_name', 'id')

                for i in results:
                    i['id'] = i['id']
                    i['UserID'] = i['username']
                    i['UserName'] = i['last_name']
                    i['UserExt'] = i['ext']
                    i['OrgName'] = i['tbuserorg__org__org_name']
                    i['OrgCode'] = i['tbuserorg__org__org_code']
                    i['Date'] = datetime.datetime.now().strftime('%Y-%m-%d')
                    i['Datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                        'tbuserorg__org__org_code']
                    list1.append(i)

                return response_origin({"status": status_code.HTTP_200_OK, "data": list1},
                                       status=status_code.HTTP_200_OK)
            else:
                page = request.GET.get('page', 1)
                results = TbUser.objects.filter(Q(username=Userid) | Q(last_name__contains=Userid) | Q(
                    tbuserorg__org__org_name__contains=Userid)).filter(status_id=100).values('id', 'username',
                                                                                             'ext',
                                                                                             'tbuserorg__org__org_code',
                                                                                             'tbuserorg__org__org_name',
                                                                                             'last_name')
                # print(len(results))
                # for i in results:
                #     i['UserID'] = i['username']
                #     i['UserName'] = i['last_name']
                #     i['UserExt'] = i['ext']
                #     i['OrgName'] = i['tbuserorg__org__org_name']
                #     i['OrgCode'] = i['tbuserorg__org__org_code']
                #     i['Date'] = datetime.datetime.now().strftime('%Y-%m-%d')
                #     i['Datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                #     del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                #         'tbuserorg__org__org_code']
                #     list1.append(i)
                #
                # return response_origin({"status": status_code.HTTP_200_OK, "data": list1, 'page': None},
                #                        status=status_code.HTTP_200_OK)
                if page:
                    paginator = Paginator(results, 15)
                else:
                    paginator = Paginator(results, len(results))
                    page = 1
                for i in paginator.page(page):
                    i['UserID'] = i['username']
                    i['UserName'] = i['last_name']
                    i['UserExt'] = i['ext']
                    i['OrgName'] = i['tbuserorg__org__org_name']
                    i['OrgCode'] = i['tbuserorg__org__org_code']
                    i['Date'] = datetime.datetime.now().strftime('%Y-%m-%d')
                    i['Datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    del i['username'], i['ext'], i['last_name'], i['tbuserorg__org__org_name'], i[
                        'tbuserorg__org__org_code']
                    list1.append(i)
                return response_origin({"status": status_code.HTTP_200_OK, "data": list1, 'page':
                    {'count': paginator.count, 'page': int(page), 'page_number': paginator.page_range[-1]}},
                                       status=status_code.HTTP_200_OK)

        except Exception as e:
            return response_origin({"status": status_code.HTTP_406_NOT_ACCEPTABLE, "message": str(e)},
                                   status=status_code.HTTP_406_NOT_ACCEPTABLE)


@api_view(http_method_names=["GET", "POST", "PUT", "DELETE"])
@log(__name__)
def drafts(request):
    if request.method == "POST":
        try:

            host_ip = request.META['HTTP_HOST']
            data = request.data
            content = data['content']
            tmpl_id = data['tmpl_id']
            alias = data['alias'] if 'alias' in data.keys() else None
            wfs = data['data'] if 'data' in data.keys() else None
            name = TbForms.objects.filter(id=tmpl_id).values('table_name')[0]['table_name']
            filelist = []
            for i in range(1, 7):
                filename = request.FILES.get('filename' + str(i), None)

                if filename == None:
                    fileurl = None
                    url_name = None
                else:

                    file = str(filename).split('.')
                    url_name = file[0] + '(' + str(uuid.uuid4()) + str(i) + ')' + '.' + file[-1]
                    path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, url_name)  #

                    with open(path, 'wb') as flhd:
                        flhd.write(filename.read())
                        flhd.close()

                    fileurl = {'href': 'http://' + host_ip + settings.FORMS_URL + url_name, 'name': str(filename)}
                filelist.append(fileurl)
                # up_file.append(url_name)
            t = TbFormdraft()
            t.creator = request.user
            t.table_name = name
            t.table_content = content
            t.tmpl_id = tmpl_id
            t.create_time = t.modify_time = datetime.datetime.now()
            t.status = 1
            t.file1 = filelist[0]
            t.file2 = filelist[1]
            t.file3 = filelist[2]
            t.file4 = filelist[3]
            t.file5 = filelist[4]
            t.file6 = filelist[5]
            t.alias = alias
            t.wfs = wfs
            t.save()
            return response_origin({"status": 1, "mes": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "errmsg": str(e)}, status=status_code.HTTP_201_CREATED)
    if request.method == 'GET':
        try:
            results = TbFormdraft.objects.filter(status=1, creator=request.user)
            list1 = []
            if results:
                for i in results:
                    dicts = {'id': i.id, 'table_name': i.table_name, 'creator': i.creator, \
                             'create_time': i.create_time.strftime('%Y-%m-%d %H:%M:%S'), \
                             'modify_time': i.modify_time.strftime('%Y-%m-%d %H:%M:%S'),
                             'status': i.status, 'alias': i.alias}
                    list1.append(dicts)
            return response_origin({"status": 1, "data": list1, 'message': "Succuess"}, status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "data": None, 'errmes': str(e)}, status=status_code.HTTP_200_OK)


@api_view(http_method_names=['GET', 'PUT', 'DELETE', "POST"])
@log(__name__)
def draft(request, pk):
    if request.method == 'GET':
        try:
            results = TbFormdraft.objects.filter(id=pk, creator=request.user).values('id', 'table_name', 'tmpl__desc',
                                                                                     'tmpl__workflow_id', 'tmpl_id',
                                                                                     'tmpl__workflow__name', 'alias',
                                                                                     'table_content', 'creator',
                                                                                     'create_time', 'modify_time',
                                                                                     'status', 'file1', 'file2', 'wfs',
                                                                                     'file3', 'file4', 'file5', 'file6')
            list1 = []

            for i in results:
                i['create_time'] = i['create_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"])
                i['modify_time'] = i['modify_time'].strftime(settings.REST_FRAMEWORK["DATETIME_FORMAT"])
                i['file1'] = eval(str(i['file1']))
                i['file2'] = eval(str(i['file2']))
                i['file3'] = eval(str(i['file3']))
                i['file4'] = eval(str(i['file4']))
                i['file5'] = eval(str(i['file5']))
                i['file6'] = eval(str(i['file6']))
                i['draft_id'] = i['id']
                i['id'] = i['tmpl_id']
                i['desc'] = i['tmpl__desc']
                # i['workflow'] = {'workflow_id': i['tmpl__workflow_id'], 'workflow_name': i['tmpl__workflow__name']}
                i['data'] = i['wfs']
                del i['tmpl__desc'], i['tmpl__workflow_id'], i['tmpl__workflow__name'], i['tmpl_id'], i['wfs']
                list1.append(i)
            return response_origin({"status": 1, "data": list1, 'message': "Succuess"}, status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "data": None, 'errmsg': str(e)}, status=status_code.HTTP_200_OK)
    if request.method == "POST":
        try:
            host_ip = request.META['HTTP_HOST']
            data = request.data
            content = data['content']
            alias = data['alias'] if 'alias' in data.keys() else None
            wfs = data['data'] if 'data' in data.keys() else None
            now = datetime.datetime.now()
            filelist = []
            for i in range(1, 7):
                filename = request.FILES.get('filename' + str(i), None)
                # print(filename,333333)
                name = 'file' + str(i)
                if filename == None:
                    fileurl = TbFormdraft.objects.filter(id=pk).values(name)[0][name]
                    url_name = None
                else:

                    file = str(filename).split('.')
                    url_name = file[0] + '(' + str(uuid.uuid4()) + str(i) + ')' + '.' + file[-1]
                    path = os.path.join(settings.MEDIA_ROOT, settings.FORMS_FILE, url_name)  #

                    with open(path, 'wb') as flhd:
                        flhd.write(filename.read())
                        flhd.close()

                    fileurl = {'href': 'http://' + host_ip + settings.FORMS_URL + url_name, 'name': str(filename)}
                filelist.append(fileurl)
            TbFormdraft.objects.filter(id=pk).update(table_content=content, modify_time=now, file1=filelist[0],
                                                     file2=filelist[1], file3=filelist[2], file4=filelist[3],
                                                     file5=filelist[4], file6=filelist[5], alias=alias, wfs=wfs)
            return response_origin({"status": 1, "message": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "errmsg": str(e)},
                                   status=status_code.HTTP_201_CREATED)
    if request.method == "DELETE":
        try:
            TbFormdraft.objects.filter(id=pk).update(status=0)
            return response_origin({"status": 1, "message": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "errmsg": str(e)},
                                   status=status_code.HTTP_201_CREATED)


@api_view(http_method_names=['GET', 'PUT', 'DELETE', "POST"])
@log(__name__)
def file_delete(request):
    if request.method == "POST":
        try:
            data = request.data
            id = data['id']
            file1 = int(data['file1']) if 'file1' in data.keys() else 0
            file2 = int(data['file2']) if 'file2' in data.keys() else 0
            file3 = int(data['file3']) if 'file3' in data.keys() else 0
            file4 = int(data['file4']) if 'file4' in data.keys() else 0
            file5 = int(data['file5']) if 'file5' in data.keys() else 0
            file6 = int(data['file6']) if 'file6' in data.keys() else 0
            if file1:
                TbFormdraft.objects.filter(id=id).update(file1=None)
            if file2:
                TbFormdraft.objects.filter(id=id).update(file2=None)
            if file3:
                TbFormdraft.objects.filter(id=id).update(file3=None)
            if file4:
                TbFormdraft.objects.filter(id=id).update(file4=None)
            if file5:
                TbFormdraft.objects.filter(id=id).update(file5=None)
            if file6:
                TbFormdraft.objects.filter(id=id).update(file6=None)
            return response_origin({"status": 1, "message": 'Success'},
                                   status=status_code.HTTP_200_OK)
        except Exception as e:
            return response_origin({"status": 0, "errmsg": str(e)},
                                   status=status_code.HTTP_201_CREATED)
